<!-- EDX插样 -->
<template>
  <el-dialog title="EDX检测插样" width="1200" center :model-value="modelValue" @close="commEvent.onClose">
    <!-- 表格 -->
    <el-table :data="forms.tableData" border class="edx-table">
      <el-table-column prop="holeNo" label="孔号" align="center" min-width="80">
        <template #default="{ row }">
          <span>{{ row.holeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实验名称" align="center" min-width="150">
        <template #default="{ row }">
          <el-input v-model="row.sampleName" placeholder="手动填写" />
        </template>
      </el-table-column>
      <el-table-column label="实验定量" align="center" min-width="120">
        <template #default="{ row }">
          <el-select v-model="row.qualitative" placeholder="请选择" @change="commEvent.handleRowChange(row)">
            <el-option label="定性" value="1" />
            <el-option label="定量" value="2" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="组别" align="center" min-width="120">
        <template #default="{ row }">
          <el-select v-model="row.group" placeholder="请选择" @change="commEvent.handleRowChange(row)">
            <el-option label="用户组" value="1" />
            <el-option label="系统组" value="2" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="检测编号" align="center" min-width="120">
        <template #default="{ row }">
          <el-select v-model="row.detectionNo" placeholder="请选择" @change="commEvent.handleRowChange(row)">
            <el-option label="1200" value="1200" />
            <el-option label="1300" value="1300" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="250">
        <template #default="{ row, $index }">
          <el-button type="primary" link size="small" @click="commEvent.onAdd($index)">新增</el-button>
          <el-button type="primary" link size="small" @click="commEvent.onCopy(row, $index)">复制</el-button>
          <el-button type="danger" link size="small" @click="commEvent.onDelete(row, $index)">删除</el-button>
          <el-button v-if="row.status === 'completed'" type="primary" link size="small" @click="commEvent.onReEdit(row)">
            重新录入
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"

interface EdxRow {
  id: string
  holeNo: number
  sampleName: string
  qualitative: string
  group: string
  detectionNo: string
  status: "editing" | "completed" // editing: 编辑中, completed: 检测完成
}

const props = defineProps({
  modelValue: { type: Boolean, default: false }
})
const emit = defineEmits(["update:modelValue", "refresh"])

// 参数
const forms = ref({
  tableData: [] as EdxRow[]
})

// 初始化表格数据（默认只有1条）
const initTableData = () => {
  forms.value.tableData = [
    {
      id: `edx-${Date.now()}`,
      holeNo: 1,
      sampleName: "",
      qualitative: "",
      group: "",
      detectionNo: "",
      status: "editing" as const
    }
  ]
}

// 获取下一个孔号
const getNextHoleNo = () => {
  if (forms.value.tableData.length === 0) return 1
  return Math.max(...forms.value.tableData.map(row => row.holeNo)) + 1
}

// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },

  // 提交
  onSubmit: () => {
    // 校验填写的数据
    const filledRows = forms.value.tableData.filter(row => row.sampleName || row.qualitative || row.group || row.detectionNo)

    if (filledRows.length === 0) {
      ElMessage.warning("请至少填写一条数据")
      return
    }

    // 校验填写的行是否完整
    const incompleteRows = filledRows.filter(row => !row.sampleName || !row.qualitative || !row.group || !row.detectionNo)

    if (incompleteRows.length > 0) {
      ElMessage.error("请填写完整的样品信息（样品名称、定性/定量、组别、检测编号）")
      return
    }

    // 校验：检测完成的行不能修改
    const editingCompletedRows = filledRows.filter(row => row.status === "completed")
    if (editingCompletedRows.length > 0) {
      ElMessage.error("检测完成的数据不能修改，请使用重新录入功能")
      return
    }

    // 确认提示
    ElMessageBox.confirm("本次检测保存后会直接执行，请确认是否已完成材料准备？", "确认提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        ElMessage.success("保存成功")
        commEvent.onClose()
      })
      .catch(() => {
        // 用户取消操作
      })
  },

  // 行数据变化
  handleRowChange: (row: EdxRow) => {
    // 可以在这里添加实时校验逻辑
  },

  // 新增行（在当前行下面插入）
  onAdd: (index: number) => {
    if (forms.value.tableData.length >= 10) {
      ElMessage.warning("最多只能添加10条数据")
      return
    }

    const newRow: EdxRow = {
      id: `edx-${Date.now()}`,
      holeNo: getNextHoleNo(),
      sampleName: "",
      qualitative: "",
      group: "",
      detectionNo: "",
      status: "editing"
    }
    forms.value.tableData.splice(index + 1, 0, newRow)
    ElMessage.success("新增成功")
  },

  // 复制行（在当前行下面插入）
  onCopy: (row: EdxRow, index: number) => {
    if (forms.value.tableData.length >= 10) {
      ElMessage.warning("最多只能添加10条数据")
      return
    }

    const newRow: EdxRow = {
      id: `edx-${Date.now()}`,
      holeNo: getNextHoleNo(),
      sampleName: row.sampleName,
      qualitative: row.qualitative,
      group: row.group,
      detectionNo: row.detectionNo,
      status: "editing"
    }
    forms.value.tableData.splice(index + 1, 0, newRow)
    ElMessage.success("复制成功")
  },

  // 重新录入（仅当检测完成时可用）
  onReEdit: (row: EdxRow) => {
    if (row.status !== "completed") {
      ElMessage.warning("只有检测完成的数据才能重新录入")
      return
    }

    // 清空该行数据，恢复为编辑状态
    row.sampleName = ""
    row.qualitative = ""
    row.group = ""
    row.detectionNo = ""
    row.status = "editing"
    ElMessage.success("已恢复为编辑状态")
  },

  // 删除行
  onDelete: (row: EdxRow, index: number) => {
    if (row.status === "completed") {
      ElMessage.error("检测完成的数据不能删除")
      return
    }

    forms.value.tableData.splice(index, 1)
    ElMessage.success("已删除该行数据")
  }
}

watch(
  () => props.modelValue,
  val => {
    if (val) {
      nextTick(() => {
        if (forms.value.tableData.length === 0) {
          initTableData()
        }
      })
    }
  }
)

// 初始化
initTableData()
</script>

<style lang="scss" scoped>
.w-full {
  width: 100%;
}
.edx-table {
  margin-bottom: 20px;
  :deep(.el-table__header) {
    th {
      font-weight: 600;
      color: #303133;
      background-color: #f5f7fa;
    }
  }
  :deep(.el-table__body) {
    tr {
      &:hover > td {
        background-color: #f5f7fa !important;
      }
    }
    td {
      padding: 12px 0;
    }
  }
}
.edx-list {
  display: flex;
  align-items: center;
  width: 100%;
  .list-label {
    flex-shrink: 0;
    font-size: 14px;
  }
  .list-value {
    flex: 1;
  }
}
</style>
